package ecomm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ecomm.entity.Permission;
import ecomm.entity.Role;
import ecomm.mapper.PermissionMapper;
import ecomm.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@Transactional
public class PermissionServiceImpl
        extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {
    @Autowired
    private PermissionMapper mapper;
    @Override
    public List<Permission> getPermissionsByPage(Page<Permission> page) {
        return mapper.selectList( page,  null);
    }

    @Override
    public IPage<Permission> getPermissionsByPage(IPage<Permission> page, String keyword) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)){
            wrapper.like("perm_name", keyword)
                    .or().like("perm_key", keyword);
        }
        return mapper.selectPage(page, wrapper);
    }
    @Override
    public List<Permission> getPermissionsByUserId(Long userId) {
        // 实际项目中，判断逻辑会包含查找是否有用户，用户是否授权，用户是否被禁用
        //此逻辑判断加分项，自行添加
        return mapper.getPermissionsByUserId(userId);
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        // 逻辑判断作为加分项，自行添加
        return mapper.getPermissionsByRoleId(roleId);
    }

    @Override
    public Set<String> getPermissionsByUserId(Long userId, String separator) {
        List<Permission> permissions = getPermissionsByUserId(userId);
        return list().stream()
                .map(Permission::getPermKey)
                .collect(Collectors.toSet());
    }

    @Override
    public Set<String> getPermissionsByRoleId(Long roleId, String separator) {
        // 此方法为加分项，自行添加
        return null;
    }


    public IPage<Permission> search(Page<Permission> page, String keyword) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like("name", keyword)
                    .or().like("role_key", keyword);
        }
        return mapper.selectPage(page, wrapper);
    }
}